package com.example.mallorder.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author guanglin.ma
 * @date 2024-01-08 17:14
 */
@Configuration
public class OrderFeginConfig {


    /**
     * fegin调用请求头会丢失，导致到其他服务无法通过认证
     * 本地线程能拿到
     * 异步执行进入到这里的线程是异步的线程，所以也拿不到请求信息
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
                String cookie = httpServletRequest.getHeader("Cookie");
                requestTemplate.header("Cookie", cookie);
            }
        };
    }
}
